import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import morgan from 'morgan';
import compression from 'compression';
import rateLimit from 'express-rate-limit';
import path from 'path';
import { config } from './config';
import { errorHandler } from './middleware/errorHandler';
import { authRoutes } from './routes/auth';
import { userRoutes } from './routes/users';
import { knowledgeBaseRoutes } from './routes/knowledgeBase';
import { categoryRoutes } from './routes/categories';
import { tagRoutes } from './routes/tags';
import { searchRoutes } from './routes/search';
import { uploadRoutes } from './routes/upload';
import { analyticsRoutes } from './routes/analytics';
import menuRoutes from './routes/menu';
import { settingsRoutes } from './routes/settings';

const app = express();
const PORT = config.PORT || 4000;

// 安全中间件
app.use(helmet());

// CORS 配置
app.use(cors({
  origin: config.CORS_ORIGINS,
  credentials: true
}));

// 请求限制
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15分钟
  max: 1000, // 限制每个IP 15分钟内最多1000个请求
  message: '请求过于频繁，请稍后再试'
});
app.use('/api/', limiter);

// 日志中间件
app.use(morgan('combined'));

// 压缩中间件
app.use(compression());

// 解析请求体
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 静态文件服务 - 提供头像文件访问
app.use('/uploads', (req, res, next) => {
  // 设置CORS头，允许跨域访问静态文件
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  
  // 处理预检请求
  if (req.method === 'OPTIONS') {
    return res.sendStatus(200);
  }
  
  next();
}, express.static(path.join(__dirname, '../uploads')));

// 确保头像目录存在
import fs from 'fs';
const avatarDir = path.join(__dirname, '../uploads/avatars');
if (!fs.existsSync(avatarDir)) {
  fs.mkdirSync(avatarDir, { recursive: true });
}

// 健康检查
app.get('/health', (req, res) => {
  res.json({ 
    status: 'ok', 
    timestamp: new Date().toISOString(),
    uptime: process.uptime()
  });
});

// 占位符头像接口
app.get('/api/placeholder/avatar', (req, res) => {
  // 生成一个简单的 SVG 占位符头像
  const svg = `
    <svg width="80" height="80" viewBox="0 0 80 80" xmlns="http://www.w3.org/2000/svg">
      <rect width="80" height="80" fill="#e5e7eb"/>
      <circle cx="40" cy="30" r="12" fill="#9ca3af"/>
      <path d="M 20 70 Q 40 50 60 70" stroke="#9ca3af" stroke-width="3" fill="none"/>
    </svg>
  `;
  
  res.setHeader('Content-Type', 'image/svg+xml');
  res.setHeader('Cache-Control', 'public, max-age=31536000');
  res.send(svg);
});

// API 路由
app.use('/api/auth', authRoutes);
app.use('/api/users', userRoutes);
app.use('/api/knowledge-base', knowledgeBaseRoutes);
app.use('/api/categories', categoryRoutes);
app.use('/api/tags', tagRoutes);
app.use('/api/search', searchRoutes);
app.use('/api/upload', uploadRoutes);
app.use('/api/analytics', analyticsRoutes);
app.use('/api/menu', menuRoutes);
app.use('/api/settings', settingsRoutes);

// 404 处理
app.use('*', (req, res) => {
  res.status(404).json({ 
    success: false, 
    error: '接口不存在' 
  });
});

// 错误处理中间件
app.use(errorHandler);

// 启动服务器
app.listen(PORT, () => {
  console.log(`🚀 后端服务已启动，端口: ${PORT}`);
  console.log(`📊 健康检查: http://localhost:${PORT}/health`);
  console.log(`🔗 API 文档: http://localhost:${PORT}/api`);
});

export default app;
